/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.autosalon.ui.automobil.action;

import com.autosalon.DAO.DaoFactory;
import com.autosalon.model.Kategorie;
import com.autosalon.model.Model;
import com.autosalon.model.Vyrobce;
import com.autosalon.tools.Constants;
import com.autosalon.ui.automobil.Automobil;
import com.autosalon.ui.automobil.state.AutomobilStateHolder;
import com.vaadin.ui.Button.ClickEvent;

/**
 *  Trida slouzici k ulozeni modelu do databaze
 * @author Petr Kriegisch
 */
public class SaveModelAction extends AbstractAutomobilAction {

    Model model;
    String nazev;

    public SaveModelAction(Automobil automobil) {
        super(automobil);
    }

    @Override
    public void buttonClick(ClickEvent event) {
        nazev = automobil.getLblNazevModelu().getValue().toString();
        try {
            if (!nazev.equals("")) {
                model = new Model();
                model.setNazev_modelu(nazev);
                Vyrobce vyrobce = (Vyrobce) DaoFactory.getinstance().getVyrobce().getOneByParam(Constants.DB_VYROBCE_NAZEV_VYROBCE, automobil.getCbVyberVyrobceProModel().getValue().toString());
                model.setVyrobce(vyrobce);
                Kategorie kategorie = (Kategorie) DaoFactory.getinstance().getKategorie().getOneByParam(Constants.DB_KATEGORIE_TYP_KAROSERIE, automobil.getCbVyberKategoriiProModel().getValue().toString());
                model.setKategorie(kategorie);
                DaoFactory.getinstance().getAutomobil().insert(model);
                automobil.getWindow().showNotification("Model uspesne vlozen");
                automobil.initFormNewModel();
                int id;
                try {
                    id = automobil.getSwitcher().getMainWindow().getZakaznik().getRole().getId().intValue();
                } catch (NullPointerException e) {
                    id = 1;
                }
                automobil.naplneniVsechTabulek();
                AutomobilStateHolder.setState(AutomobilStateHolder.VIEW_AUTOMOBIL_STATE, id, automobil);
            } else {
                automobil.getWindow().showNotification("Vlozene udaje jsou chybne");
            }
        } catch (NumberFormatException e) {
            automobil.getWindow().showNotification("Vlozene udaje jsou chybne");
        } catch (IndexOutOfBoundsException in) {
            automobil.getWindow().showNotification("Vlozene udaje jsou chybne");
        } catch (NullPointerException np) {
            automobil.getWindow().showNotification("Vlozene udaje jsou chybne");
        }
    }
}
